
import router from './router'
import { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      // 跳转到主页
      next('/') // 中转到主页
      // next（地址）并没有执行后置守卫
      NProgress.done()
      return
    }

    // 有token 但是没有用户信息 就获取用户信息
    if (!store.getters.name) {
      await store.dispatch('user/getUserInfoAction')
      // 1.3 先获取用户有什么菜单
      const user = store.state.user
      const menus = user.userInfo.roles.menus // 配置的权限列表, menus是前端路由路径不带/  employee /employee

      console.log('menus  ----->  ', menus)
      console.log('asyncRoutes  ----->  ', asyncRoutes)

      // 1.4. 过滤出有权限的路由
      const newList = asyncRoutes.filter(v => {
        return menus.includes(v.name)
      })
      console.log('  ----->  ', newList)

      // 1.5addRoutes追加路由 类似数组的push
      router.addRoutes([...newList, { path: '*', redirect: '/404', hidden: true }])

      // 4. 把路由更新到vuex中
      store.commit('user/setRoutes', newList)
      // 1. 修复Vue2中路由bug,  addRoutes之后要调用一下next(to.path)
      next(to.path)
    }
    next()
    return
  }

  if (whiteList.includes(to.path)) {
    next()
    return
  }
  // 2.2 去的不是白名单, 直接跳转到登录页

  next('/login')
  NProgress.done()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

